/**
 * $Id: Compiler.java 15 2009-01-19 02:21:28Z vic.fryzel $ 
 */

package compiler;

import java.util.*;
import java.io.*;
import parser.*;

/**
 * Compiles the given program from stdin or the file specified as the first
 * command-line arguemnt.
 * 
 * @author Vic Fryzel <vef3240@rit.edu>
 */
public class Compiler {
	/**
	 * The main method. Simply collects input from stdin (terminated by EOF,) or
	 * the file specified by the first command-line argument, creates a parse
	 * tree using the Parser class, and compiles the parse tree while executing
	 * nodes. Compiled output is printed to stdout. This method was modified
	 * from the Parser main method, which was auto-generated by pj2.
	 * 
	 * @param args
	 *            This program takes no command line arguments. Give input via
	 *            stdin.
	 */
	public static void main(String[] args) {
		InputStream in = System.in;
		if(args.length >= 1) {
			try {
				in = new FileInputStream(new File(args[0]));
			} catch(IOException e) {
				System.err.println(e.getMessage());
			}
		}

		Parser.yyInput scanner = new Parser.yyLex(in);
		try {
			java.lang.Object parser = scanner.getClass().getEnclosingClass()
					.newInstance();
			// args[0]: if specified, toggle null storage
			if (args != null && args.length > 0) {
				java.lang.reflect.Field yyAddNull = parser.getClass().getField(
						"yyAddNull");
				yyAddNull.setBoolean(parser,
						yyAddNull.getBoolean(parser) ^ true);
			}
			// build tree, dump
			java.lang.Object tree = parser.getClass().getMethod(
					"yyparse",
					new java.lang.Class[] { Parser.yyInput.class,
							java.lang.Object[].class }).invoke(parser, scanner,
					new java.lang.Object[] { new Parser.yyTree() });
			Collection<Parser.yyTree.Visit> yyTree = (Collection<Parser.yyTree.Visit>) tree;
			CompilerElementDoVisitor visitor = new CompilerElementDoVisitor();
			visitor.visit((Parser.yyTree.Program) yyTree);
		} catch (java.lang.NoSuchFieldException e) {
			System.err.println("cannot create parser [" + e + "]");
			System.exit(1);
		} catch (java.lang.InstantiationException e) {
			System.err.println("cannot create parser [" + e + "]");
			System.exit(1);
		} catch (java.lang.IllegalAccessException e) {
			System.err.println("cannot create parser [" + e + "]");
			System.exit(1);
		} catch (java.lang.NoSuchMethodException e) {
			System.err.println("cannot create parser [" + e + "]");
			System.exit(1);
		} catch (java.lang.reflect.InvocationTargetException e) {
			System.err.println("parse error [" + e + "]");
			System.exit(1);
		}
	}
}
